import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import { addCartAPI, getCartListAPI, deleteCartAPI } from '@/apis/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {

    const { isToken } = useUserStore()

    // 购物车基础数据
    const cartList = ref([])

    // 商品总数
    // a => 计数器  c => 项
    const totalCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    
    // 商品总价
    const totalPrice = computed(() => cartList.value.reduce((a, c) => a + c.price * c.count, 0))

    // 已选中的商品数量
    const selectedCount = computed(() => cartList.value.reduce((a, c) => a + (c.selected ? c.count : 0), 0))


    // 获取购物车列表
    const getCartList = async () => {
         // 渲染购物车列表
         const res = await getCartListAPI()
         cartList.value = res.result // 覆盖本地的购物车
    }

    // 清空本地购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 添加购物车
    const addCart =  async (goods) => {
        const { skuId, count } = goods
        
        // 接口购物车
        if (isToken) {
            await addCartAPI({ skuId, count })
            getCartList()
        } else {
            // 判断是否添加过该商品 => 将参数中的id和本地id进行比较 => 如果有，则存在
            const item = cartList.value.find((item) => item.skuId === goods.skuId)
            if (item) {
                // 存在 => count + 1
                item.count++
            } else {
                // 没添加过 => 追加
                cartList.value.push(goods)
            }
        }
        
        
    }
    // 全选
    const isAll = computed(() => cartList.value.every((item) => item.selected === true))

    // 反选
    const onAll = (selected) => {
        cartList.value.forEach((item) => item.selected = selected)
    }
 
    // 切换选中状态
    const changeSelect = (skuId) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = !item.selected
    }

    // 移除购物车
    const removeCart = async (skuId) => {
        if (isToken) {
            await deleteCartAPI([skuId])
            // 消息提醒
            ElMessage.success('删除成功')
            // 重新渲染数据
            getCartList()
        } else {
            // cartList.value.filter((item) => item.skuId !== skuId)
            const index = cartList.value.findIndex((item) => item.skuId === skuId)
            cartList.value.splice(index, 1)
        }
        
    }

    return {
        cartList,
        totalCount,
        totalPrice,
        isAll,
        selectedCount,
        getCartList,
        onAll,
        clearCart,
        changeSelect,
        addCart,
        removeCart
    }
}, {
    persist: true // 开启数据持久化
})